
import axios from 'axios';

import React, { useState, useRef,useEffect } from "react";
import { Button, Space, NavBar, Toast } from 'antd-mobile';
import '../css/audio.css'
import { useNavigate } from 'react-router-dom';

const RecordView = () => {
  const [audioUrl, setAudioUrl] = useState('');
  const [url, setUrl] = useState('')
  const [id,setId]=useState('')
  const medisStream = useRef();
  const recorder = useRef();
  const mediaBlobs = useRef([]);
  const navigate = useNavigate();
  // 开始
  const startRecord = async () => {
    // 读取输入流
    medisStream.current = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
    // 生成 MediaRecorder 对象
    recorder.current = new MediaRecorder(medisStream.current);
    console.log(recorder.current);

    // 将 stream 转成 blob 来存放
    recorder.current.ondataavailable = (blobEvent) => {
      mediaBlobs.current.push(blobEvent.data);
    };
    console.log(mediaBlobs.current);

    // 停止时生成预览的 blob url
    recorder.current.onstop = () => {
      const blob = new Blob(mediaBlobs.current, { type: 'audio/wav' });
      const mediaUrl = URL.createObjectURL(blob);
      setAudioUrl(mediaUrl);
      console.log(mediaUrl);
      setUrl(mediaUrl)



    };

    recorder.current?.start();
  };
  useEffect(() => {
    const basic = JSON.parse(localStorage.getItem('basicFact'));
      setId(basic._id)
      console.log(id);
  }, []);
  const add = () => {
    axios.post('http://127.0.0.1:3000/update', {id:id, url: url }).then(res => {
      console.log(res.data.data.url);

    })
  }
  const stopRecord = async () => {
    recorder.current?.stop();
    medisStream.current?.getTracks().forEach((track) => track.stop());
  };
  const right = (
    <div>
      <Space >
        预览
      </Space>
    </div>
  )

  const back = () => {
    Toast.show({
      icon: 'loading',
      content: '加载中...',
      duration: 1000,
    })
    navigate('/overview')
  }
  return (
    <div>
      <div className='top'>
        <NavBar right={right} onBack={back}>
          简历
        </NavBar>
      </div>
      <div>
        <div className='audio'>
          <audio src={audioUrl} controls />
        </div>
        <div className='button'>
          <Button color='warning' style={{ marginRight: '10px' }} onClick={startRecord}>开始</Button>
          <Button color='warning' style={{ marginLeft: '10px' }} onClick={stopRecord}>停止</Button>
        </div>

        <div className='button'>
          <Button color='warning' style={{ width: '150px' }} onClick={() => add()} >保存</Button>
        </div>
      </div>


    </div>
  );
};

export default RecordView;